package hu.szyrt.bug.connections;

import hu.szyrt.bug.utils.Config;
import hu.szyrt.bug.utils.Crypto;
import hu.szyrt.bug.utils.Utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;

import android.os.Handler;
import android.util.Log;

public class BaseConnection extends Thread {

	private final static String SHA1_SALT = "Bud4S4ltP3st";
	private final static String AUTHORIZATION_USERNAME = "BUG_Android",
								AUTHORIZATION_PASSWORD = "Bud4P3st";
	
	
	private Handler handler;
	protected String url;
	protected HashMap<String, String> params = new HashMap<String, String>();
	
	protected String rawResults;
	protected String errorText;
	protected Notify notify;
		
	public BaseConnection(String url) {
		this.handler = new Handler();
		this.url = url;
		setLanguage(Locale.getDefault().getLanguage());
		setPriority(NORM_PRIORITY - 1);
	}
	
	
	protected void parameterizedURL(){
		// Paraméerek
		ArrayList<String> params_serialized = new ArrayList<String>();		
		try {
			for(String key : params.keySet())
				params_serialized.add(key + "=" + URLEncoder.encode(params.get(key), "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		// Link kiegészítése
		if(params_serialized.size() > 0)
			url += "?" + Utils.join(params_serialized, "&");
		
	}
	
	protected boolean download(){
		try {			
			URL downloadURL = new URL(url);			
			
			// TODO: remove
			Log.d("bug", downloadURL.toExternalForm());
			
			Authenticator.setDefault(new Authenticator(){				
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(AUTHORIZATION_USERNAME, AUTHORIZATION_PASSWORD.toCharArray());
				}
			});
			HttpURLConnection.setFollowRedirects(true);
			HttpURLConnection conn = (HttpURLConnection)downloadURL.openConnection();							   
							   conn.setRequestMethod("GET");	
							   conn.setConnectTimeout(Config.CONNECTION_TIMEOUT);
							   conn.setReadTimeout(Config.CONNECTION_TIMEOUT);
							   conn.connect();
			Log.d("bug", "result:   " + conn.getResponseCode());
			if(conn.getResponseCode() == 200){
				InputStream is = conn.getInputStream();
				this.rawResults = Utils.inputStreamToString(is);
				conn.disconnect();
				return true;
			}else{
				errorText = conn.getResponseMessage();
				conn.disconnect();
				return false;
			}
		} catch (MalformedURLException e) {
			errorText = e.getMessage();
			e.printStackTrace();
			return false;
		} catch(SocketTimeoutException e){
			errorText = "Server not respond.";
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			errorText = e.getMessage();
			e.printStackTrace();
			return false;
		}
	}
	
	
	protected String salterize(String value){
		return Crypto.sha1Hex(value + SHA1_SALT);
	}

	public void setLanguage(String language){
		this.params.put("lang", Utils.supportedLanguage(language));
	}
	
	public void setNotify(Notify notify) {
		this.notify = notify;
	}
	
	public String getErrorText() {
		return errorText;
	}
	
	
	public interface Notify{
		void onSuccess();
		void onError();
	}	
	
	protected void postSuccess(){
		if(notify != null){
			this.handler.post(new Runnable() {
				public void run() {
					notify.onSuccess();
				}
			});
		}
	}
	
	protected void postError(){
		if(notify != null){
			this.handler.post(new Runnable() {
				public void run() {
					notify.onError();
				}
			});
		}
	}
}
